package admin.controllers;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.StaffModel;

import admin.data.StaffData;
import admin.forms.StaffForm;

public class EditStaffServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		TreeMap check = new TreeMap();
		StaffData staffData = new StaffData();
		StaffModel user = new StaffModel();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		
		String username = "";
		try {
			username = URLDecoder.decode(path.toLowerCase().replaceAll("/admin/staff/edit/", ""),"UTF-8");
		} catch (Exception e) {
			response.sendRedirect("/admin/staff/list");
		}
		
		user = (StaffModel) staffData.getStaff(username);
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/admin/pages/form_staff.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		StaffData uData = new StaffData();
		StaffModel user = new StaffModel();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		
		String username = "";
		try {
			username = URLDecoder.decode(path.toLowerCase().replaceAll("/admin/staff/edit/", ""),"UTF-8");
		} catch (Exception e) {
			response.sendRedirect("/admin/staff/list");
		}
		
		user = uData.getStaff(username);
		
		//Check value valid form
		request.setAttribute("action", "edit");
		StaffForm userForm = new StaffForm();
		TreeMap forms = (TreeMap) userForm.checkValid(request, user); 
		user = (StaffModel) forms.get("user");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if(check.size() == 0)
	    {
			uData.insert(user);
			request.setAttribute("success", "Cập nhật thành công thông tin tài khoản " + user.getUsername());
	    }
		
		request.setAttribute("form", "edit");
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/admin/pages/form_staff.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
		
		
	}
}
